﻿using Newtonsoft.Json;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace XjjXmm.FrameWork.Cache
{
    public class RedisClient
    {
        public static readonly RedisClient Instance = new RedisClient();

        private ConnectionMultiplexer _connectionMultiplexer;
        private IDatabase _db;
        public async Task Init(string connectionString)
        {

            if (_connectionMultiplexer == null)
            {
                _connectionMultiplexer = await ConnectionMultiplexer.ConnectAsync(connectionString);
                _db = _connectionMultiplexer.GetDatabase();

                // _db.ListRightPushAsync
            }

        }

        public async Task<long> ListRightPush<T>(string key, T value, When when = When.Always, CommandFlags flags = CommandFlags.None)
        {
            var json = JsonConvert.SerializeObject(value);
            return await _db.ListRightPushAsync(key, json, when, flags);
        }

        public async Task<T?> ListRightPop<T>(string key, CommandFlags flags = CommandFlags.None)
        {
            var redisValue = await _db.ListRightPopAsync(key, flags);
            return JsonConvert.DeserializeObject<T>(redisValue);
        }

        public async Task<long> ListRightPush(string key, string value, When when = When.Always, CommandFlags flags = CommandFlags.None)
        {

            return await _db.ListRightPushAsync(key, value, when, flags);
        }

        public async Task<string?> ListRightPop(string key, CommandFlags flags = CommandFlags.None)
        {
            var redisValue = await _db.ListRightPopAsync(key, flags);
            return redisValue;
        }

        public async Task<bool> HashSet(string key, string field, string value)
        {
            return await _db.HashSetAsync(key, field, value);
        }

        public async Task<string> HashSet(string key, string field)
        {
            return await _db.HashGetAsync(key, field);
        }

        public async Task<bool> HashSet<T>(string key, string field, T value)
        {
            var json = JsonConvert.SerializeObject(value);

            return await _db.HashSetAsync(key, field, json);
        }

        public async Task<T?> HashSet<T>(string key, string field)
        {
            var redisValue = await _db.HashGetAsync(key, field);
            return JsonConvert.DeserializeObject<T>(redisValue);
        }
    }
}
